package com.jboost.modules.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baidu.aip.ocr.AipOcr;
import com.jboost.common.util.HttpRestUtils;
import com.jboost.modules.app.dto.GptReq;
import com.jboost.modules.app.dto.resp.GptResp;
import com.jboost.modules.app.dto.resp.InvoiceInfo;
import com.jboost.modules.app.service.ChatGptService;
import com.jboost.modules.system.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.compress.utils.Lists;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.http.HttpHeaders;

import org.springframework.stereotype.Service;

import okhttp3.*;
import org.json.JSONObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.util.UUID;
@Service
@Slf4j
public class ChatGptServiceImpl implements ChatGptService {
    final static String url = "https://welynk.cn/gpt/azure/chat";
    // 配置信息
    private static final String APP_ID = "119857862";
    private static final String API_KEY = "QxLHUKdevLOKPnZDRtx6XYtc";
    private static final String SECRET_KEY = "rU1XOtXc2qfSIKndTjrpiR3OMVz1W5yg";





    public String requsetGpt(String msg)  {
        GptReq gptReq = new GptReq();
        gptReq.setSession_key(UUID.randomUUID().toString());
        gptReq.setList(Lists.newArrayList());
        GptReq.GptMsg gptMsg = new GptReq.GptMsg();
        gptMsg.setMsg(msg);
        gptMsg.setFrom_user(true);
        HttpHeaders jdyHeaders = new HttpHeaders();
        gptReq.getList().add(gptMsg);
        String post = null;
        try {
            post = HttpRestUtils.post(url, BeanUtil.beanToMap(gptReq),jdyHeaders);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        GptResp gptResp = JSONUtil.toBean(post, GptResp.class);
        return gptResp.getData().getList().get(0).getMsg();
    }

    @Override
    public InvoiceInfo requsetInvoice(String url) throws UnsupportedEncodingException, ParseException {

        url = URLDecoder.decode(url, StandardCharsets.UTF_8.toString());
        // 初始化客户端
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);


        JSONObject response = client.vatInvoice(downloadAndConvertToJpg(url), null);

        // 转换为对象
        InvoiceInfo invoiceInfo = InvoiceInfo.fromJsonResult(response);
        if (InvoiceInfo.containsInvalidChars(invoiceInfo.getPurchaserName())) {
            invoiceInfo.setPurchaserName(InvoiceInfo.fixStringEncoding(invoiceInfo.getPurchaserName()));
        }

        // 使用识别结果
        System.out.println("发票代码: " + invoiceInfo.getInvoiceCode());
        System.out.println("发票号码: " + invoiceInfo.getInvoiceNum());
        log.info("销方名称: " + invoiceInfo.getSellerName());
        log.info("shou方名称: " + invoiceInfo.getPurchaserName());
        return invoiceInfo;
    }


    /**
     * 从URL下载文件并根据需要转换为JPG
     * @param fileUrl 文件URL
     * @return JPG文件路径
     */
    private String downloadAndConvertToJpg(String fileUrl) {
        try {
            // 创建临时文件（先用tmp扩展名）
            File tempFile = File.createTempFile("invoice_", ".tmp");
            String filePath = tempFile.getAbsolutePath();

            // 下载文件
            InputStream in = new URL(fileUrl).openStream();
            Files.copy(in, Paths.get(filePath), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
            in.close();

            // 检测文件真实类型
            String fileType = detectFileType(filePath);

            // 重命名文件为正确的扩展名
            File renamedFile = new File(filePath.substring(0, filePath.lastIndexOf('.')) + "." + fileType);
            tempFile.renameTo(renamedFile);
            String finalFilePath = renamedFile.getAbsolutePath();

            // 如果是PDF则转换为JPG
            if ("pdf".equalsIgnoreCase(fileType)) {
                File tempJpgFile = File.createTempFile("invoice_", ".jpg");
                String jpgFilePath = tempJpgFile.getAbsolutePath();
                convertPdfToJpg(finalFilePath, jpgFilePath);
                renamedFile.delete(); // 删除临时PDF文件
                return jpgFilePath;
            } else {
                // 如果已经是图片格式，直接返回
                return finalFilePath;
            }
        } catch (IOException e) {
            throw new RuntimeException("下载或转换文件失败: " + e.getMessage(), e);
        }
    }

    /**
     * 检测本地文件类型
     * @param filePath 文件路径
     * @return 文件类型
     */
    private String detectFileType(String filePath) {
        try (InputStream in = new FileInputStream(filePath)) {
            byte[] header = new byte[10];
            int bytesRead = in.read(header);

            if (bytesRead >= 4) {
                // PDF文件头: %PDF
                if (header[0] == 0x25 && header[1] == 0x50 && header[2] == 0x44 && header[3] == 0x46) {
                    return "pdf";
                }
                // JPEG文件头: FF D8 FF
                if (header[0] == (byte) 0xFF && header[1] == (byte)  0xD8 && header[2] == (byte) 0xFF) {
                    return "jpg";
                }
                // PNG文件头: 89 50 4E 47
                if (header[0] == (byte) 0x89 && header[1] == 0x50 && header[2] == 0x4E && header[3] == 0x47) {
                    return "png";
                }
            }
            // 默认为pdf
            return "pdf";
        } catch (Exception e) {
            return "pdf";
        }
    }


    /**
     * 获取文件类型
     * @param fileUrl 文件URL
     * @return 文件扩展名
     */
    private String getFileType(String fileUrl) {
        String url = fileUrl.toLowerCase();
        if (url.contains(".pdf")) {
            return "pdf";
        } else if (url.contains(".jpg") || url.contains(".jpeg")) {
            return "jpg";
        } else if (url.contains(".png")) {
            return "png";
        } else {
            // 默认假设是PDF（可根据需要调整）
            return "pdf";
        }
    }

    /**
     * 使用ImageMagick将PDF转换为JPG
     * 需要系统安装ImageMagick
     * @param pdfFilePath PDF文件路径
     * @param jpgFilePath 输出JPG文件路径
     */
    /**
     * 将PDF文件转换为JPG图片（多种方法备选）
     * @param pdfFilePath PDF文件路径
     * @param jpgFilePath 输出JPG文件路径
     */
    private void convertPdfToJpg(String pdfFilePath, String jpgFilePath) {
        // 首先尝试使用PDFBox
        try {
            convertPdfToJpgWithPDFBox(pdfFilePath, jpgFilePath);
            return;
        } catch (Exception e) {
            log.warn("PDFBox转换失败，尝试Ghostscript: " + e.getMessage());
        }

        // 如果都失败，抛出异常
        throw new RuntimeException("所有PDF转换方法都失败了");
    }

    /**
     * 使用PDFBox转换（优化版本）
     */
    private void convertPdfToJpgWithPDFBox(String pdfFilePath, String jpgFilePath) {
        try {
            System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider");

            PDDocument document = PDDocument.load(new File(pdfFilePath));
            PDFRenderer pdfRenderer = new PDFRenderer(document);

            // 使用高质量渲染
            BufferedImage image = pdfRenderer.renderImageWithDPI(0, 300,
                    org.apache.pdfbox.rendering.ImageType.RGB);

            // 应用渲染提示
            java.awt.Graphics2D g2d = image.createGraphics();
            g2d.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING,
                    java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2d.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING,
                    java.awt.RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(java.awt.RenderingHints.KEY_FRACTIONALMETRICS,
                    java.awt.RenderingHints.VALUE_FRACTIONALMETRICS_ON);
            g2d.dispose();

            ImageIO.write(image, "jpg", new File(jpgFilePath));
            document.close();
        } catch (IOException e) {
            throw new RuntimeException("PDFBox转换失败: " + e.getMessage(), e);
        }
    }



    /**
     * 注册系统字体以支持中文渲染
     */
    private void registerFonts() {
        try {
            // 添加系统字体目录
            String os = System.getProperty("os.name").toLowerCase();
            if (os.contains("win")) {
                // Windows系统字体目录
                addFontDirectory("C:/Windows/Fonts/");
            } else if (os.contains("mac")) {
                // macOS系统字体目录
                addFontDirectory("/System/Library/Fonts/");
                addFontDirectory("/Library/Fonts/");
            } else {
                // Linux系统字体目录
                addFontDirectory("/usr/share/fonts/");
                addFontDirectory("/usr/local/share/fonts/");
            }
        } catch (Exception e) {
            log.warn("注册系统字体时出错: " + e.getMessage());
        }
    }

    /**
     * 添加字体目录
     * @param fontDir 字体目录路径
     */
    private void addFontDirectory(String fontDir) {
        try {
            File dir = new File(fontDir);
            if (dir.exists() && dir.isDirectory()) {
                File[] fontFiles = dir.listFiles((d, name) ->
                        name.toLowerCase().endsWith(".ttf") ||
                                name.toLowerCase().endsWith(".ttc") ||
                                name.toLowerCase().endsWith(".otf"));

                if (fontFiles != null) {
                    for (File fontFile : fontFiles) {
                        try {
                            // 注册字体到系统
                            java.awt.Font font = java.awt.Font.createFont(
                                    java.awt.Font.TRUETYPE_FONT, fontFile);
                            // 这里主要是为了触发字体加载
                        } catch (Exception e) {
                            // 忽略单个字体加载失败
                        }
                    }
                }
            }
        } catch (Exception e) {
            // 忽略字体目录处理错误
        }
    }

}
